import {
  ActionType,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable
} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Drawer, message, Popconfirm} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import type {SortOrder} from 'antd/es/table/interface';
import {
  deleteBorrowRecordUsingPost,
  listBorrowRecordVoByPageUsingPost,
  updateBorrowRecordUsingPost
} from "@/services/backend/borrowRecordController";
import UpdateModal from "@/pages/Admin/BorrowRecordManage/components/UpdateModal";


const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  // const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.BorrowRecordVO>();
  const [activeKey, setActiveKey] = useState<string>();
  const [openConfirm, setOpenConfirm] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: API.BorrowRecordVO) => {
    if (!currentRow) {
      return;
    }
    const hide = message.loading('修改中');
    try {
      await updateBorrowRecordUsingPost({
        id: currentRow.id,
        ...fields,
      });
      hide();
      message.success('操作成功');
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('操作失败' + error.message);
      return false;
    }
  };

  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  /*const handleAdd = async (fields: API.BorrowRecordAddRequest) => {
    const hide = message.loading('正在添加');
    try {
      await addBorrowRecordUsingPost({
        ...fields,
      });
      hide();
      message.success('创建成功');
      handleModalVisible(false);
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('创建失败，' + error.message);
      return false;
    }
  };*/

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param record
   */
  const handleRemove = async (record: API.BorrowRecordVO) => {
    const hide = message.loading('正在删除');
    if (!record) return true;
    try {
      const res = await deleteBorrowRecordUsingPost({
        id: record.id,
      });
      hide();
      if (res.code === 0)
        message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  useEffect(() => {
    // 当 currentRow 变化时，更新数据
    if (showDetail && currentRow) {
      setCurrentRow(undefined)
    }
  }, [currentRow, showDetail]);

  const columns: ProColumns<API.BorrowRecordVO>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      valueType: 'index',
      width: 50,
    },
    // {
    //   title: '分类',
    //   dataIndex: 'categoryId',
    //   valueType: 'text',
    //   valueEnum: valueEnum,
    //   // hideInTable: true,
    // },
    {
      title: '书名',
      dataIndex: 'title',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '借阅人',
      dataIndex: 'userName',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '出版社',
      dataIndex: 'publisher',
      valueType: 'text',
      hideInTable: true,
      hideInForm: true,
      search: false,
    },
    {
      title: '出版日期',
      dataIndex: 'publishDate',
      valueType: 'date',
      hideInTable: true,
      search: false,
      hideInForm: true,
    },
    {
      title: '价格',
      dataIndex: 'price',
      valueType: 'money',
      hideInTable: true,
      hideInForm: true,
      search: false,
    },
    {
      title: '作者',
      dataIndex: 'author',
      valueType: 'text',
      hideInTable: true,
      hideInForm: true,
      search: false,
    },
    {
      title: '分类名',
      dataIndex: 'categoryName',
      valueType: 'text',
      hideInForm: true,
      search: false,
    },
    {
      title: '借阅状态',
      dataIndex: 'brStatus',
      valueType: 'text',
      valueEnum: {
        'borrowed': {text: '未归还', status: 'Processing'},
        'returned': {text: '已归还', status: 'Success'},
        'overdue': {text: '逾期未还', status: 'Error'}
      },
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
      search: false
    },
    {
      title: '用户头像',
      dataIndex: 'userAvatar',
      valueType: 'image',
      /*render: (_, record) => (
        <img src={record.userAvatar} alt={record.userName} style={{width: 50}}/>
      ),*/
      hideInTable: true,
      hideInForm: true,
      search: false,
    },
    {
      title: '用户账号',
      dataIndex: 'userAccount',
      valueType: 'text',
      hideInTable: true,
      hideInForm: true,
    },
    {
      title: '用户邮箱',
      dataIndex: 'email',
      valueType: 'text',
      hideInTable: true,
      hideInForm: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      valueType: 'text',
      hideInTable: true,
      hideInForm: true,
    },
    {
      title: '用户简介',
      dataIndex: 'userProfile',
      valueType: 'text',
      hideInTable: true,
      hideInForm: true,
      search: false,
    },
    {
      title: '用户角色',
      dataIndex: 'userRole',
      valueType: 'text',
      hideInTable: true,
      hideInForm: true,
      valueEnum: {
        user: {
          text: '用户',
          status: 'Default',
        },
        admin: {
          text: '管理员',
          status: 'Processing',
        },
        ban: {
          text: '禁用',
          status: 'danger',
        },
      },
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInForm: true,
      sorter: true,
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => [
        <Button
          size={'small'}
          type={'text'}
          key="edit"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          修改
        </Button>,
        <Popconfirm
          key="borrow"
          title="你确认删除吗"
          disabled={openConfirm}
          onConfirm={() => {
            handleRemove(record);
            setOpenConfirm(false)
          }}
          onCancel={() => {
            setOpenConfirm(false)
          }}
        >
          <Button type={'text'}
                  size={'small'}
                  danger
                  key="removeBtn"
                  onClick={() => {
                    setOpenConfirm(true)
                  }}
          >
            删除
          </Button>
        </Popconfirm>,
        <Button
          type={'text'}
          size={'small'}
          key="show"
          onClick={() => {
            setCurrentRow(record);
            setShowDetail(true)
          }}
        >
          详情
        </Button>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        
        pagination={{
          pageSize: 10,
        }}
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey={currentRow?.id?.toString() || undefined}
        search={{
          labelWidth: 100,
        }}
        // dataSource={categoryList}
        // toolBarRender={() => [
        //   <Button
        //     type="primary"
        //     key="primary"
        //     onClick={() => {
        //       handleModalVisible(true);
        //     }}
        //   >
        //     <PlusOutlined/> 新建
        //   </Button>,
        // ]}
        toolbar={{
          menu: {
            activeKey: activeKey,
            items: [
              {
                key: '',
                label: <span>全部</span>,
              },
              {
                key: 'borrowed',
                label: <span>未归还</span>,
              },
              {
                key: 'returned',
                label: <span>已归还</span>,
              },
              {
                key: 'overdue',
                label: <span>逾期未还</span>,
              },
            ],
            onChange: (key: any) => {
              setActiveKey(key);
              if (actionRef.current) {
                actionRef.current?.reload();
              }
            }
          }
        }}
        // @ts-ignore
        request={async (
          params: {
            pageSize?: number | undefined;
            current?: number | undefined;
            keyword?: string | undefined;
          },
          sort: Record<string, SortOrder>,
          filter: Record<string, React.ReactText[] | null>,
        ) => {
          let sortFieldStr = "";
          let sortOrderStr: any;
          if (Object.keys(sort).length > 0) {
            const [firstSort] = Object.entries(sort); // 获取sort对象的第一个键值对
            sortFieldStr = firstSort[0];
            sortOrderStr = firstSort[1];
          }
          const res = await listBorrowRecordVoByPageUsingPost({
            ...params,
            sortField: sortFieldStr,
            sortOrder: sortOrderStr,
            brStatus: activeKey,
          });
          if (res?.data) {
            return {
              data: res?.data.list || [],
              success: true,
              total: res?.data.total,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        // @ts-ignore
        columns={columns}
      />
      <UpdateModal
        columns={columns}
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalVisible(false);
            // console.log(currentRow)
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        visible={updateModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={300}
        visible={showDetail}
        onClose={() => {
          setShowDetail(false);
          setCurrentRow(undefined);
        }}
        closable={false}
        title={"详情"}
      >
        <ProDescriptions
          column={1}
          title={"借阅信息"}
          request={async () => ({
            data: currentRow || {},
          })}
          // dataSource={{currentRow} || {}}
          // params={{
          //   id: currentRow?.id,
          // }}
          params={{
            id: currentRow?.id,
          }}
          columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
        />
        <Button
          onClick={() => {
            setCurrentRow(undefined);
            setShowDetail(false)
          }}
          type={"primary"}>关闭</Button>
      </Drawer>

      {/* <Drawer
        width={300}
        visible={showDetail}
        onClose={async () => {
          await setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
        title={"详情"}
      >
        <ProDescriptions
          column={2}
          title={"借阅人" + currentRow?.userName}
          request={async () => ({
            data: currentRow || {},
          })}
          // dataSource={{currentRow} || {}}
          // params={{
          //   id: currentRow?.id,
          // }}
          columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
        />
        <Button
          onClick={async () => {
            setShowDetail(false)
            await setCurrentRow(undefined);
          }}
          type={"primary"}>关闭</Button>
      </Drawer>*/}
      {/*<CreateModal
        columns={columns}
        onCancel={() => {
          handleModalVisible(false);
        }}
        // @ts-ignore
        onSubmit={(values) => {
          // @ts-ignore
          handleAdd(values);
        }}
        visible={createModalVisible}
      />*/}
    </PageContainer>
  );
};
export default TableList;
